package com.ofps.web.controller.flow;

import java.text.ParseException;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ofps.flow.domain.Dto.FlowInfoDto;
import com.ofps.flow.domain.Dto.InsertFlowInfoDto;
import com.ofps.flow.domain.EnterFlowNode;
import com.ofps.flow.service.IEnterFlowNodeService;
import com.ofps.forms.common.utils.R;
import com.ofps.forms.service.MyUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ofps.common.annotation.Log;
import com.ofps.common.core.controller.BaseController;
import com.ofps.common.core.domain.AjaxResult;
import com.ofps.common.enums.BusinessType;
import com.ofps.flow.domain.EnterFlowInfo;
import com.ofps.flow.service.IEnterFlowInfoService;
import com.ofps.common.utils.poi.ExcelUtil;
import com.ofps.common.core.page.TableDataInfo;

/**
 * 流程信息Controller
 * flow_info：某个流程的基本信息
 * ● id：流程唯一标识
 * ● name：该流程的名称
 * ● user_id：建立该流程的用户(一般是某公司的管理员，有该权限的一些人)（动态路由、权限管理）
 * ● dept_id：该流程隶属的部门id
 * ● form_id：该流程关联的表单id
 * ● nodes：流程节点数
 *
 * @author ofps
 * @date 2022-06-01
 */
@RestController
@RequestMapping("/flowInfo")
public class EnterFlowInfoController extends BaseController {
    @Autowired
    private IEnterFlowInfoService enterFlowInfoService;
    @Autowired
    private MyUserService myUserService;
    @Autowired
    private IEnterFlowNodeService iEnterFlowNodeService;
    /**
     * 查询流程列表
     * 分页查询 筛选条件
     */

    @RequestMapping("/list")
    public R list(@RequestBody FlowInfoDto flowInfo) {
        return enterFlowInfoService.myList(flowInfo);
    }

    /**
     * 导出流程列表
     */
    @PreAuthorize("@ss.hasPermi('flowInfo:export')")
    @Log(title = "流程", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EnterFlowInfo enterFlowInfo) {
        List<EnterFlowInfo> list = enterFlowInfoService.selectEnterFlowInfoList(enterFlowInfo);
        ExcelUtil<EnterFlowInfo> util = new ExcelUtil<EnterFlowInfo>(EnterFlowInfo.class);
        util.exportExcel(response, list, "流程数据");
    }

    /**
     * 获取流程详细信息
     */
    @PreAuthorize("@ss.hasPermi('flowInfo:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(enterFlowInfoService.getById(id));
    }

    /**
     * 新增流程
     */
    @PreAuthorize("@ss.hasPermi('flowInfo:add')")
    @Log(title = "流程", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EnterFlowInfo enterFlowInfo) {
        return toAjax(enterFlowInfoService.save(enterFlowInfo));
    }

    /**
     * 修改流程
     */
    @PreAuthorize("@ss.hasPermi('flowInfo:edit')")
    @Log(title = "流程", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EnterFlowInfo enterFlowInfo) {
        return toAjax(enterFlowInfoService.updateById(enterFlowInfo));
    }

    /**
     * 删除流程
     */
    @PreAuthorize("@ss.hasPermi('flowInfo:remove')")
    @Log(title = "流程", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(enterFlowInfoService.removeByIds(Arrays.asList(ids)));
    }

    @RequestMapping("/queryWithDeptId")
    @RequiresPermissions("flowInfo:queryWithDeptId")
    public R queryWithDeptId(@RequestBody Map<String,Object> body){
        List<Object> flowInfo = new ArrayList<>();
        List<EnterFlowInfo> enterFlowInfos = enterFlowInfoService.queryWithDeptId(body);
        for(EnterFlowInfo enterFlowInfo : enterFlowInfos){
            Map<String,Object> Infos = new HashMap<>();
            if(null != enterFlowInfo.getFlowInfo())
                Infos.put("flowInfo" , enterFlowInfo.getFlowInfo());
            else
                Infos.put("flowInfo" , null);
            if(null != enterFlowInfo.getFlowIden())
                Infos.put("flowIden" , enterFlowInfo.getFlowIden());
            else
                Infos.put("flowIden" , null);
            if(null != enterFlowInfo.getDeptId())
                Infos.put("deptId" , enterFlowInfo.getDeptId());
            else
                Infos.put("deptId" , null);
            if(null != enterFlowInfo.getId())
                Infos.put("id" , enterFlowInfo.getId());
            else
                Infos.put("id" , null);
            if(null != enterFlowInfo.getUserId()){
                Infos.put("userName",myUserService.queryUserNameWithUserId(enterFlowInfo.getUserId().toString()));
                Infos.put("nickName",myUserService.queryNickNameWithUserId(enterFlowInfo.getUserId().toString()));
            }
            else{
                Infos.put("userName",null);
                Infos.put("nickName",null);
            }
            if(null != enterFlowInfo.getFormId())
                Infos.put("formId" , enterFlowInfo.getFormId());
            else
                Infos.put("formId" , null);
            if(null != enterFlowInfo.getName())
                Infos.put("name" , enterFlowInfo.getName());
            else
                Infos.put("name" , null);
            if(null != enterFlowInfo.getNodes())
                Infos.put("nodes" , enterFlowInfo.getNodes());
            else
                Infos.put("nodes" , null);
//            if(null != enterFlowInfo.getCreateBy())
//                Infos.put("createBy" , enterFlowInfo.getCreateBy());
//            else
//                Infos.put("createBy" , null);
//            if(null != enterFlowInfo.getCreateTime())
//                Infos.put("createTime" , enterFlowInfo.getCreateTime().toString());
//            else
//                Infos.put("createTime" , null);
//            if(null != enterFlowInfo.getDeleted())
//                Infos.put("deleted" , enterFlowInfo.getDeleted().toString());
//            else
//                Infos.put("deleted" , null);
//            if(null != enterFlowInfo.getParams())
//                Infos.put("params" , enterFlowInfo.getParams().toString());
//            else
//                Infos.put("params" , null);
//            if(null != enterFlowInfo.getRemark())
//                Infos.put("remark" , enterFlowInfo.getRemark().toString());
//            else
//                Infos.put("remark" , null);
//            if(null != enterFlowInfo.getSearchValue())
//                Infos.put("searchValue" , enterFlowInfo.getSearchValue().toString());
//            else
//                Infos.put("searchValue" , null);
//            if(null != enterFlowInfo.getUpdateBy())
//                Infos.put("updateBy" , enterFlowInfo.getUpdateBy().toString());
//            else
//                Infos.put("updateBy" , null);
//            if(null != enterFlowInfo.getUpdateTime())
//                Infos.put("updateTime" , enterFlowInfo.getUpdateTime().toString());
//            else
//                Infos.put("updateTime" , null);
            flowInfo.add(Infos);
        }
        if (null == flowInfo)
            return R.ok("暂无信息!");
        else
            return R.ok("查询成功!").put("flowInfo",flowInfo);
    }

    @RequestMapping("/insertFlowInfoAndFlowNodes")
    public R Insert(@RequestBody InsertFlowInfoDto insertFlowInfoDto) {
        EnterFlowInfo enterFlowInfo = insertFlowInfoDto.getFlowInfo();
        System.out.println(enterFlowInfo);

//        Map<String, Object> flowInfo = (Map<String, Object>) nodesInfo.get("flowInfo");
//        //检测是否主键重复
        Boolean flag = enterFlowInfoService.insert(enterFlowInfo);
        if (flag) return R.ok("flowIden重复！");
        List<EnterFlowNode> flowNodes = insertFlowInfoDto.getFlowNodes();
        for (EnterFlowNode node : flowNodes) {
            iEnterFlowNodeService.insert(node);
        }

//        List<Map<String, Object>> nodes = (List<Map<String, Object>>) nodesInfo.get("flowNodes");
//        for (Map<String, Object> node : nodes) {
//            iEnterFlowNodeService.InsertNode(node);
//        }
        return R.ok("插入成功!");
    }
}
